package com.zyd.blog.homeart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zyd.blog.homeart.service.Address.BaService;
import com.zyd.blog.homeart.service.BaseService;
import com.zyd.blog.homeart.service.IPhotoService;
import com.zyd.blog.homeart.service.qo.TempleUserUploadQo;
import com.zyd.blog.homeart.util.AppConstant;
import com.zyd.blog.homeart.util.ResponseCode;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * @author liusongqi
 */
@Service
public class PhotoServiceImpl extends BaseService implements IPhotoService {

    @Autowired
     private BaService baService;
    @Override
    public String upload(List<MultipartFile> listFile, String userId) throws Exception {
        int size = 1;
        List<String> imgUrlList = new ArrayList<>();
        String jpg = "jpg";
        String png = "png";
        String jpeg = "jpeg";
        String file1 = "file";
        String imageUrl = null;
        if (listFile != null && listFile.size() > 0 && listFile.size() <= size) {
            // 有文件
            for (MultipartFile file : listFile) {
                String originalFilename = file.getOriginalFilename();
                String suffix = null;
                if (originalFilename != null) {
                    suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                }
                if (!jpg.equalsIgnoreCase(suffix) && !png.equalsIgnoreCase(suffix)&& !jpeg.equalsIgnoreCase(suffix)&& !file1.equalsIgnoreCase(suffix)) {
                    throw new Exception("上传失败：文件格式不支持");
                }
                try {
                    // 处理上传文件，上传1张图片
                    String imgUrl = this.doUpload(file, "1");
                    imgUrlList.add(imgUrl);
                } catch (Exception e) {
                    throw new Exception(e.getMessage());
                }
            }
            imageUrl = imgUrlList.get(0);
        } else if (listFile != null && listFile.size() > size) {
            throw new Exception(String.format("对不起，只能上传%d张图片！", size));
        }
        return imageUrl;
    }
    @Override
    public String doUpload(MultipartFile file, String userId) throws Exception {
        try {
            String appId = AppConstant.TempleSystemConstant.APP_ID;
            String appSecret = AppConstant.TempleSystemConstant.APP_SECRET;
            String bucketName = AppConstant.TempleSystemConstant.BUCKET_NAME;
            //创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String url = baService.GET_TOKEN_URL;
            TempleUserUploadQo templeUserUploadQo = new TempleUserUploadQo();
            templeUserUploadQo.setAppId(appId);
            templeUserUploadQo.setAppSecret(appSecret);
            HttpEntity<TempleUserUploadQo> entity = new HttpEntity<>(templeUserUploadQo, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
            // {"code":"200","msg":"success","data":"4ba4a27d3d004825adfd9e442ed5e587"}
            String result = responseEntity.getBody();
            JSONObject resultObj = JSON.parseObject(result);
            Integer code = resultObj.getInteger("code");
            String token = "";
            if (code == ResponseCode.SUCCESS) {
                token = resultObj.getString("data");
            }
            // 临时文件夹
            String tempPath = AppConstant.Name("1");
            String uploadUrl = baService.FILE_UPLOAD_URL;
            // 设置请求头
            HttpHeaders uploadHeaders = new HttpHeaders();
            uploadHeaders.setContentType(MediaType.parseMediaType("multipart/form-data;charset=UTF-8"));

            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            // 保存临时文件
            List<String> tempList = new ArrayList<>();
            createDir(tempPath);
            String originalFilename = file.getOriginalFilename();
            String[] split = originalFilename.split("\\.");
            String tempFilePath = tempPath + UuidUtils.getUUID()+"."+split[split.length-1];
            try {
                // create local temp file
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(tempFilePath));
                tempList.add(tempFilePath);
                // MultipartFile 直接转 FileSystemResource是不行的,把临时文件变成FileSystemResource
                FileSystemResource resource = new FileSystemResource(tempFilePath);
                // LinkedMultiValueMap中，key对应的value值其实是一个LinkedList，所以可以一直往同一个key中add值，不会覆盖
                param.add("file", resource);
            } catch (Exception e) {
                logger.error("保存文件{}至本地临时文件异常!", file.getOriginalFilename(), e);
            }
            param.add("appId", appId);
            param.add("bucketName", bucketName);
            param.add("platformId", "1");
            param.add("token", token);
            // 发送请求，这里的restTemplate是通过@Autowired注入的
            HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, uploadHeaders);
            String uploadResult = restTemplate.postForObject(uploadUrl, formEntity, String.class);
            // delete local temp file
            tempList.add(tempPath);
            deleteLocalTempFiles(tempList);
            // {"code":"200","msg":"success","data":{"successFile":["Temple/tmpad1.png"],"errorFile":[]}}
            JSONObject imageResult = JSON.parseObject(uploadResult);
            Integer c = imageResult.getInteger("code");

            if (c == ResponseCode.SUCCESS) {
                JSONArray successFiles = imageResult.getJSONObject("data").getJSONArray("successFile");
                System.out.println(baService.DOMAIN_NAME+successFiles.getString(0));
            }
            return tempFilePath;
        } catch (Exception e) {
            throw new Exception("上传失败");
        }
    }



    private void deleteLocalTempFiles(List<String> tempList) {
        if (!CollectionUtils.isEmpty(tempList)) {
            for (String fileName : tempList) {
                new File(fileName).delete();
            }
        }
    }

    private void createDir(String tempPath) {
        File file = new File(tempPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
